package idv.arthur.work;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * Servlet implementation class DelMRitem
 */ 
public class ManipulateGridHosts extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public ManipulateGridHosts() {
        super();
        // TODO Auto-generated constructor stub
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	doPost(request,response);
    }

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		request.setCharacterEncoding("UTF-8");
		
		Widgets wid = new Widgets();
		Connection conn = wid.getConn(true);
		PreparedStatement ps = null;
		ResultSet rs = null;
		
		String strSQL = "";
		String oper = request.getParameter("oper");									//增刪改查那一種
		String bssId =  request.getParameter("bss");								//系統ID
		String subSysId = request.getParameter("subSys");					//子系統ID
		String hostIP = request.getParameter("hostIP");							//主機IP
		String hostName = request.getParameter("hostName");				//主機名稱
		int port = Integer.parseInt(request.getParameter("port"));		//PORT
		String result = "";
		String currentUser = "842297";
		
		
		
		/** 判別需進行何種操作 **/
		if ( "del".equalsIgnoreCase(oper) ) {
			strSQL = "DELETE FROM hosts WHERE hostip=? AND subsysid=? AND bssid=? AND port=?";
			try {
				ps = conn.prepareStatement(strSQL);
				ps.setString(1, hostIP);
				ps.setString(2, subSysId);
				ps.setString(3, bssId);
				ps.setInt(4, port);
				ps.execute();
				
				wid.keepLogProfile(wid.HOST, wid.DELETE, currentUser, conn, ps);
				result = "刪除了"+hostIP;
			} catch (SQLException e) {
				result = "刪除"+hostIP+"失敗!!\n\n";
				result += wid.errProcess(e);
			}
		} else if ( "add".equalsIgnoreCase(oper) ) {
			try {
				if (! isDuplicated(bssId,subSysId,hostIP,port,conn,ps,rs) ) {
					strSQL = "INSERT INTO hosts (hostip,subsysid,bssid,port,hostname,creator,createdDateTime) VALUES (?,?,?,?,?,?,?)";
					ps = conn.prepareStatement(strSQL);
					ps.setString(1, hostIP);
					ps.setString(2, subSysId);
					ps.setString(3, bssId);
					ps.setInt(4, port);
					ps.setString(5, hostName);
					ps.setString(6, currentUser);
					ps.setTimestamp(7, wid.currentTimeStamp());
					ps.execute();
					
					wid.keepLogProfile(wid.HOST, wid.ADD, currentUser, conn, ps);
					result = "新增完成 "+hostIP;
				} else {
					result = hostIP+" 已存在 !";		
				}
			} catch (SQLException e) {
				result = "新增"+hostIP+"失敗!!\n\n";
				result += wid.errProcess(e);
			}
		} else if ( "edit".equalsIgnoreCase(oper) ) {
			String oriBssId = request.getParameter("oriBssId");			
			String oriSubSysId = request.getParameter("oriSubSysId");
			String oriHostIP = request.getParameter("oriHostIP");
			int oriPort = Integer.parseInt(request.getParameter("oriPort"));

			/** 這四個主鍵值有一個不一樣 **/
			boolean isDifferent = (!oriBssId.equalsIgnoreCase(bssId) || !oriSubSysId.equalsIgnoreCase(subSysId) || !oriHostIP.equalsIgnoreCase(hostIP) || oriPort != port);
			
			/**	先確認要變更後的值，其主鍵並非已經存在 **/
			try {
				/**	有不一樣但沒重覆  或是  沒有不一樣 **/
				if ( (isDifferent && !isDuplicated(bssId,subSysId,hostIP,port,conn,ps,rs)) || !isDifferent) {
					strSQL = "UPDATE hosts SET hostip=?,subsysid=?,bssid=?,port=?,hostname=?,lastUpdator=?,lastUpdatedDateTime=? WHERE hostip=? AND subsysid=? AND bssid=? AND port=?";
					
					ps = conn.prepareStatement(strSQL);
					ps.setString(1, hostIP);
					ps.setString(2, subSysId);
					ps.setString(3, bssId);
					ps.setInt(4, port);
					ps.setString(5, hostName);
					ps.setString(6, currentUser);
					ps.setTimestamp(7, wid.currentTimeStamp());
					ps.setString(8, oriHostIP);
					ps.setString(9, oriSubSysId);
					ps.setString(10, oriBssId);
					ps.setInt(11, oriPort);
					ps.execute();
					
					wid.keepLogProfile(wid.HOST, wid.UPDATE, currentUser, conn, ps);
					result = "修改完成!! "+"\n"+"系統ID："+bssId+"\n"+"子系統ID："+subSysId+"\n"+"主機IP："+hostIP+"主機名稱："+hostName+"\n"+"Port："+port+"\n";
					
				}  else {
					result = " 已存在 !!!\n"+"\n"+"系統ID："+bssId+"\n"+"子系統ID："+subSysId+"\n"+"主機IP："+hostIP+"\n"+"Port："+port+"\n";		
				}
			} catch (SQLException e) {
				result = "修改"+hostIP+"失敗!!\n\n";
				result += wid.errProcess(e);
			}
		}

		try {
			if (rs!= null) {rs.close();}
			if (ps!= null) {ps.close();}
			if (conn!= null) {conn.close();}
		} catch (SQLException e) {
			System.out.println(wid.errProcess(e));
		}
		
		response.setContentType("application/text");
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write(result);		
	}
	
	private boolean isDuplicated(String bssId,String subSysId,String hostIP,int port,Connection conn,PreparedStatement ps, ResultSet rs) throws SQLException {
		String strSQL = "SELECT COUNT(*) FROM hosts WHERE hostip=? AND subsysid=? AND bssid=? AND port=?";
		
		ps = conn.prepareStatement(strSQL);
		ps.setString(1, hostIP);
		ps.setString(2, subSysId);
		ps.setString(3, bssId);
		ps.setInt(4, port);
		rs = ps.executeQuery();
		rs.next();

		return rs.getInt(1) == 0?false:true;
	}
}